package com.hy.admin.controller.pages;

import java.io.Console;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hy.admin.domain.dto.AdminWebUserDto;
import com.hy.admin.entity.CourseEntity;
import com.hy.admin.entity.CourseSeriesEntity;
import com.hy.admin.entity.MemberEntity;
import com.hy.admin.helper.request.AccountRequest;
import com.hy.admin.helper.response.CourseResponse;
import com.hy.admin.security.service.business.SecurityCurrentUserLoader;
import com.hy.admin.security.utils.MyHttpclientUtils;
import com.hy.admin.service.AccountService;
import com.hy.admin.service.CourseSeriesService;
import com.hy.admin.service.CourseService;
import com.hy.admin.service.TeacherService;
import com.hy.core.response.ServicesResult;

@Controller
@RequestMapping("/page/teacher")
public class PageControllerTeacher extends PageControllerBase{

	@Autowired
    private AccountService accountService;
	@Autowired
	private CourseService courseServiceImpl;
	@Autowired
	private CourseSeriesService courseSeriesServiceImpl;
	@Autowired
	private TeacherService teacherServiceImpl;
	
	@Value("${security.admin.Authorization}")
	private String headerAuthorization;
	
	@ResponseBody
	@RequestMapping(value="/authen", method=RequestMethod.POST)
	public ServicesResult<MemberEntity> authen(String mobile, String password, HttpSession session,HttpServletRequest request) {
		ServicesResult<MemberEntity> result = new ServicesResult<MemberEntity>();
		if(isLogin(ROLE_TEACHER)) {
			MemberEntity memberEntity = (MemberEntity)session.getAttribute("memberEntity");
			result.setResult(memberEntity);
		}
		else {
			if(StringUtils.isBlank(mobile) || StringUtils.isBlank(password)) return result;
			
			
			try {
				Map<String, String> param = new HashMap<>();  
				param.put("grant_type", "password");
				param.put("username", mobile);
				param.put("password", password);
				ObjectMapper objectMapper=new ObjectMapper();
				String s=request.getContextPath();
				String realPath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+request.getContextPath();
				String resp = MyHttpclientUtils.doPost(realPath+"/oauth/token",headerAuthorization, param);
				AdminWebUserDto adminWebUserDto=null;
				if (StringUtils.isNotBlank(resp)) {
					adminWebUserDto = objectMapper.readValue(resp, AdminWebUserDto.class);
					MemberEntity member=adminWebUserDto.getUser().getMemberEntity();
					member.setAccess_token(adminWebUserDto.getAccess_token());
					result.setResult(member);
					markedLogin(mobile, ROLE_TEACHER);
					session.setAttribute("memberEntity", member);
				}
				
			} catch (Exception e) {
				e.printStackTrace();
			}
			
//			AccountRequest accountRequest = new AccountRequest();
//			accountRequest.setMobile(mobile);
//			accountRequest.setPassword(password);
//			result = accountService.login(accountRequest);
//			MemberEntity memberEntity = result.getResult();
//			if(memberEntity != null) {
//				markedLogin(memberEntity.getMobile(), ROLE_TEACHER);
//				session.setAttribute("memberEntity", memberEntity);
//			}
		}
		return result;
	}
	
	@RequestMapping(value={"", "/", "/login" }, method=RequestMethod.GET)
	public String toLogin(Model model, HttpSession session) {
//		if(isLogin(ROLE_TEACHER)) {
//			return "redirect:/page/teacher/courses";
//		}
		saveDefaultAttributes2Model(model);
		
		return makeViewName("login");
	}
	
	@RequestMapping(value="/courses", method=RequestMethod.GET)
	public String toTeacherCourses(Model model, HttpSession session) {
//		if(!isLogin(ROLE_TEACHER)) return "redirect:/page/teacher/login";
		SecurityCurrentUserLoader securityCurrentUserLoader=new SecurityCurrentUserLoader();
		MemberEntity memberEntity=securityCurrentUserLoader.load();
		if(memberEntity==null) {
			return "redirect:/page/teacher/login";
		}
		saveDefaultAttributes2Model(model);
//		MemberEntity memberEntity = (MemberEntity)session.getAttribute("memberEntity");
		model.addAttribute("memberEntity", memberEntity);
		if(memberEntity != null) {
			int total = courseServiceImpl.countByMemberId(memberEntity.getId());
			model.addAttribute("total", total);
			
			final int pageSize = 10;
			int totalPages = total / pageSize;
			if(total % pageSize > 0) ++totalPages;
			model.addAttribute("totalPages", totalPages);
			
			if(total > 0) {
				ServicesResult<List<CourseResponse>> servicesResult2 = courseServiceImpl.listByMemberId(memberEntity.getId(), 1, pageSize);
				List<CourseResponse> courses = servicesResult2.getResult();
				model.addAttribute("courses", courses);
			}
			else {
				model.addAttribute("courses", null);
			}
		}
		return makeViewName("courses");
	}
	
	@RequestMapping(value="/uploadCourse", method=RequestMethod.GET)
	public String toUploadCourse(Model model, HttpSession session) {
//		if(!isLogin(ROLE_TEACHER)) return "redirect:/page/teacher/login";
		SecurityCurrentUserLoader securityCurrentUserLoader=new SecurityCurrentUserLoader();
		MemberEntity memberEntity=securityCurrentUserLoader.load();
		if(memberEntity==null) {
			return "redirect:/page/teacher/login";
		}
		saveDefaultAttributes2Model(model);
		
//		MemberEntity memberEntity = (MemberEntity)session.getAttribute("memberEntity");
		model.addAttribute("memberEntity", memberEntity);
		
		List<CourseSeriesEntity> courseSeries = new LinkedList<CourseSeriesEntity>();
		CourseSeriesEntity record = new CourseSeriesEntity();
		record.setId(null);
		record.setName("无");
		courseSeries.add(record);
		
		ServicesResult<List<CourseSeriesEntity>> result = courseSeriesServiceImpl.listByMid(memberEntity.getId());
		List<CourseSeriesEntity> series = result.getResult();
		if(series != null && series.size() > 0) {
			courseSeries.addAll(series);
		}
		
		model.addAttribute("courseSeries", courseSeries);
		
		return makeViewName("uploadCourse");
	}
	
	@ResponseBody
	@RequestMapping(value="/addCourse", method=RequestMethod.POST)
	public ServicesResult<Boolean> addCourse(
			CourseEntity courseEntity, MultipartFile file, MultipartFile image) {
		ServicesResult<Boolean> servicesResult;
		try {
			servicesResult = courseServiceImpl.addWithFile(courseEntity, file, image);
		} catch (Exception e) {
			e.printStackTrace();
			servicesResult = new ServicesResult<Boolean>();
			servicesResult.setResult(false);
		}
		return servicesResult;
	}
	
	@RequestMapping(value="/courseEdit", method=RequestMethod.GET)
	public String toCourseEdit(Model model, Long memberId, Long courseId) {
//		if(!isLogin(ROLE_TEACHER)) return "redirect:/page/teacher/login";
		SecurityCurrentUserLoader securityCurrentUserLoader=new SecurityCurrentUserLoader();
		MemberEntity memberEntity=securityCurrentUserLoader.load();
		if(memberEntity==null) {
			return "redirect:/page/teacher/login";
		}
		saveDefaultAttributes2Model(model);
		
		if(memberId != null) {
			MemberEntity teacher = teacherServiceImpl.selectById(memberId);
			model.addAttribute("teacher", teacher);
		}
		
		if(courseId != null) {
			ServicesResult<CourseResponse> result = courseServiceImpl.detail(courseId, memberId);
			if(result != null && result.getResult() != null) {
				CourseResponse course = result.getResult();
				model.addAttribute("course", course);
				
				ServicesResult<List<CourseSeriesEntity>> seriesResponse = 
						courseSeriesServiceImpl.listByMid(memberId);
				List<CourseSeriesEntity> series = new LinkedList<CourseSeriesEntity>();
				
				CourseSeriesEntity record = new CourseSeriesEntity();
				record.setId(null);
				record.setName("无");
				if(course.getSeriesId() == null) {
					record.setStatus(1);
				}
				else {
					record.setStatus(0);
				}
				series.add(record );
				
				List<CourseSeriesEntity> resultList = seriesResponse.getResult();
				if(resultList != null) {
					
				}
				
				if(resultList != null && resultList.size() > 0) {
					for(CourseSeriesEntity entity : resultList) {
						if(entity.getId().equals(course.getSeriesId())) {
							entity.setStatus(1);//把课程当前系列状态置为1，以便界面选中
						}
						else {
							entity.setStatus(0);
						}
					}
					series.addAll(resultList);
				}
				
				model.addAttribute("series", series);
			}
		}
		
		return makeViewName("courseEditTeacher");
	}
	
	@Override
	protected String getViewPrefix() {
		return "teacher/";
	}
}
